<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElDropdown, ElDropdownMenu, ElDropdownItem } from 'element-plus';
import {queryInfoApi1,updatePasswordApi1} from '../api/superAdmin'
import { User, CloseBold } from '@element-plus/icons-vue'
import {queryInfoApi2,updatePasswordApi2} from '../api/consultant'


// 控制导航栏展开/收缩
const isCollapsed = ref(false);
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};

// 登录用户信息
const username = ref('');
const id = ref('');
const position = ref('');
const router = useRouter();

onMounted(() => {
  //获取当前操作用户
  const loginUser = JSON.parse(localStorage.getItem('loginUser'));
  if (loginUser && loginUser.username) {
    username.value = loginUser.username;
    id.value = loginUser.id;
    position.value = loginUser.position;
    passwordForm.value.username = loginUser.username;
  }



});



// 下拉框操作
const handleCommand = (command) => {
  if (command === 'logout') {
    ElMessage.success('退出成功');
    localStorage.removeItem('loginUser');
    router.push('/');
  } else if (command === 'personal-center'){
    personalCenterVisible.value = true;
    if (position.value === 1){//admin
      queryAdmin(id.value);
    }else { //consultant
      queryConsultant(id.value);
    }
  } else if (command === 'change-password'){
    openChangePasswordDialog();
  }else {
    ElMessage.info("我也不知什么错误");
  }
};


// 页面路径（面包屑）
const route = useRoute();
const breadcrumb = computed(() => {
  const matched = route.matched.filter((item) => item.meta && item.meta.title);
  return matched.map((item, index) => ({
    name: item.meta.title,
    path: index === 0 ? '/index' : '', // 只有首页可点击
  }));
});

// 控制弹窗是否显示
const personalCenterVisible = ref(false)

// 假设这是个人信息
const userInfo = ref({
  id: '',
  username: '',
  name: '',
  tel: ''
})

//查询superAdmin信息
const queryAdmin = async (id) =>{
  const result = await queryInfoApi1(id);
  if (result.code === 200){//成功
    userInfo.value = result.data;
  }else {
    ElMessage.error("查询失败");
  }
}

//查询consultant信息
const queryConsultant = async (id) =>{
  const result = await queryInfoApi2(id);
  if (result.code === 200){//成功
    userInfo.value = result.data;
  }else {
    ElMessage.error("查询失败");
  }
}

const changePasswordVisible = ref(false);

const passwordFormRef = ref(null);

const passwordForm = ref({
  username: '',          // 当前登录账号
  newPassword: '',
  confirmPassword: ''
});


// 点击"修改密码"时打开弹窗，填入当前账号
function openChangePasswordDialog() {
  passwordForm.value.newPassword = '';
  passwordForm.value.confirmPassword = '';
  changePasswordVisible.value = true;
}

// 校验两次密码是否一致
function validatePasswordConfirm(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入的密码不一致'));
  } else {
    callback();
  }
}

// 点击确定按钮提交
// const submitChangePassword = async () => {
//   const username = passwordForm.value.username;
//   const password = passwordForm.value.confirmPassword;
//
//   if (position.value === 1) {
//     const result = await updatePasswordApi1(username, password);
//     if (result.code === 200) {
//       ElMessage.success("修改成功");
//       const loginUser = JSON.parse(localStorage.getItem('loginUser'));
//       loginUser.password = password;
//       localStorage.setItem('loginUser', JSON.stringify(loginUser)); // ✅ 保存修改
//     } else {
//       ElMessage.error("修改失败");
//     }
//   } else {
//     const result = await updatePasswordApi2(username, password);
//     if (result.code === 200) {
//       ElMessage.success("修改成功");
//       const loginUser = JSON.parse(localStorage.getItem('loginUser'));
//       loginUser.password = password;
//       localStorage.setItem('loginUser', JSON.stringify(loginUser)); // ✅ 保存修改
//     } else {
//       ElMessage.error("修改失败");
//     }
//   }
// };
const submitChangePassword = async () => {
  const username = passwordForm.value.username;
  const password = passwordForm.value.confirmPassword;

  const updateApi = position.value === 1 ? updatePasswordApi1 : updatePasswordApi2;

  try {
    const result = await updateApi(username, password);
    if (result.code === 200) {
      ElMessage.success("修改成功");

      const loginUser = JSON.parse(localStorage.getItem('loginUser'));
      loginUser.password = password;
      localStorage.setItem('loginUser', JSON.stringify(loginUser)); // ✅ 保存修改

      changePasswordVisible.value = false; // 可选：关闭弹窗
      passwordFormRef.value.resetFields(); // 可选：清空表单
    } else {
      ElMessage.error("修改失败");
    }
  } catch (e) {
    ElMessage.error("请求出错");
    console.error(e);
  }
};



</script>

<template>
  <div class="layout-container">
    <!-- 页头 -->
    <el-header class="header">
      <div class="header-left">
        <el-button
          :icon="isCollapsed ? 'Expand' : 'Fold'"
          class="collapse-btn"
          @click="toggleCollapse"
        />
        <h1 class="header-title">十方智育后台管理系统</h1>
      </div>
      <div class="header-right">
        <el-avatar :size="40" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png" />
        <span class="username">您好，{{ username || '用户' }}</span>
        <el-dropdown @command="handleCommand">
          <span class="dropdown-link">
            <el-icon><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="personal-center">个人中心</el-dropdown-item>
              <el-dropdown-item command="change-password">修改密码</el-dropdown-item>
              <el-dropdown-item command="system-settings">系统设置</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </el-header>

    <!-- 个人中心弹窗 -->
    <el-dialog
      title="个人中心"
      v-model="personalCenterVisible"
      width="30%"
      class="personal-center-dialog"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-card shadow="hover" class="info-card animate__animated animate__fadeInDown">
        <div class="info-details">
          <h3 class="info-title">
            <el-icon><User /></el-icon> 用户信息
          </h3>
          <el-divider></el-divider>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="ID">
              <el-tag type="info">{{ userInfo.id }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="用户名">
              <el-tag type="success">{{ userInfo.username }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="姓名">
              <el-tag type="warning">{{ userInfo.name }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="电话">
              <el-tag type="danger">{{ userInfo.tel }}</el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </el-card>
      <template #footer>
        <el-button
          type="primary"
          @click="personalCenterVisible = false"
          class="close-button animate__animated animate__fadeOutUp"
        >
          <el-icon><CloseBold /></el-icon> 关闭
        </el-button>
      </template>
    </el-dialog>


    <!-- 修改密码弹框 -->
    <el-dialog
      title="修改密码"
      v-model="changePasswordVisible"
      width="30%"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
    >
      <el-form :model="passwordForm" ref="passwordFormRef" label-width="80px">
        <el-form-item label="账号">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword" :rules="[{ required: true, message: '请输入新密码', trigger: 'blur' }]">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" :rules="[
      { required: true, message: '请确认新密码', trigger: 'blur' },
      { validator: validatePasswordConfirm, trigger: 'blur' }
    ]">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="changePasswordVisible = false">取消</el-button>
        <el-button type="primary" @click="submitChangePassword">确定修改</el-button>
      </template>
    </el-dialog>





    <!-- 主体内容 -->
    <el-container class="main-container">
      <!-- 左侧导航栏 -->
      <el-aside :width="isCollapsed ? '64px' : '220px'" class="aside">
        <el-menu
          :default-active="$route.path"
          :collapse="isCollapsed"
          router
          class="nav-menu"
        >
          <!-- 网站主页 -->
          <el-menu-item index="/index">
            <el-icon><House /></el-icon>
            <span>网站主页</span>
          </el-menu-item>

          <!-- 系统管理 -->
          <el-sub-menu index="/system" v-if="position === 1">
            <template #title>
              <el-icon><Setting /></el-icon>
              <span>系统管理</span>
            </template>
            <el-menu-item index="/system/system-user">系统用户管理</el-menu-item>
            <el-menu-item index="/system/normal-user">普通用户管理</el-menu-item>
            <el-menu-item index="/system/announcement">公告管理</el-menu-item>
            <el-menu-item index="/system/company">公司管理</el-menu-item>
          </el-sub-menu>

          <!-- 课程管理 -->
          <el-sub-menu index="/course">
            <template #title>
              <el-icon><Notebook /></el-icon>
              <span>课程管理</span>
            </template>
            <el-menu-item index="/course/category">课程分类管理</el-menu-item>
            <el-menu-item index="/course/list">课程管理</el-menu-item>
            <el-menu-item index="/course/review">课程评价管理</el-menu-item>
            <el-menu-item index="/course/communication">课程留言管理</el-menu-item>
            <el-menu-item index="/course/order">课程订单管理</el-menu-item>
            <el-menu-item index="/course/purchase">课程购买记录管理</el-menu-item>
          </el-sub-menu>

          <!-- 师资管理 -->
          <el-sub-menu index="/teacher">
            <template #title>
              <el-icon><User /></el-icon>
              <span>师资管理</span>
            </template>
            <el-menu-item index="/teacher/consultant">咨询师管理</el-menu-item>
            <el-menu-item index="/teacher/level">咨询师等级管理</el-menu-item>
            <el-menu-item index="/teacher/expertise">擅长领域管理</el-menu-item>
            <el-menu-item index="/teacher/fee-category">收费分类管理</el-menu-item>
            <el-menu-item index="/teacher/fee-standard">收费标准管理</el-menu-item>
          </el-sub-menu>

          <!-- 内容管理 -->
          <el-sub-menu index="/content">
            <template #title>
              <el-icon><Document /></el-icon>
              <span>内容管理</span>
            </template>
            <el-menu-item index="/content/article">文章管理</el-menu-item>
            <el-menu-item index="/content/psychology-knowledge">心理知识管理</el-menu-item>
            <el-menu-item index="/content/fm">FM管理</el-menu-item>
            <el-menu-item index="/content/public-welfare">公益中心管理</el-menu-item>
            <el-menu-item index="/content/psychology-test">心理测评管理</el-menu-item>
          </el-sub-menu>

          <!-- 心理答疑管理 -->
          <el-sub-menu index="/qa">
            <template #title>
              <el-icon><QuestionFilled /></el-icon>
              <span>心理答疑管理</span>
            </template>
            <el-menu-item index="/qa/question">问题管理</el-menu-item>
            <el-menu-item index="/qa/reply">回复管理</el-menu-item>
          </el-sub-menu>

          <!-- 咨询预约管理 -->
          <el-sub-menu index="/appointment">
            <template #title>
              <el-icon><Calendar /></el-icon>
              <span>咨询预约管理</span>
            </template>
            <el-menu-item v-if="true" index="/appointment/list">咨询预约管理</el-menu-item>
            <el-menu-item index="/appointment/reply">咨询回复管理</el-menu-item>
            <el-menu-item index="/appointment/comment">用户评论管理</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>

      <!-- 内容区域 -->
      <el-main class="content">
        <!-- 页面路径 -->
        <el-breadcrumb separator="/">
          <el-breadcrumb-item
            v-for="(item, index) in breadcrumb"
            :key="index"
            :to="item.path"
            :style="index === 0 ? 'font-weight: bold' : ''"
          >
            {{ item.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 内容展示 -->
        <div class="content-body">
          <router-view />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<style scoped>
.layout-container {
  width: 100vw;
  height: 100vh;
  background: linear-gradient(135deg, #f5f7fa, #c3cfe2);
  margin: 0;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.header {
  background: linear-gradient(90deg, #1e3a8a, #3b82f6);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
}

.collapse-btn {
  background: linear-gradient(90deg, #409eff, #79bbff);
  border: none;
  border-radius: 12px;
  color: white;
  padding: 8px;
  margin-right: 15px;
}

.collapse-btn:hover {
  background: linear-gradient(90deg, #337ecc, #66aaff);
}

.header-title {
  font-size: 22px;
  color: white;
  font-weight: bold;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
}

.username {
  color: white;
  font-size: 16px;
  margin: 0 10px;
}

.dropdown-link {
  color: white;
  cursor: pointer;
}

.dropdown-link:hover {
  color: #d1e7ff;
}

.main-container {
  flex: 1;
  overflow: hidden;
}

.aside {
  background: #ffffff;
  border-right: 1px solid #e6e6e6;
  transition: width 0.3s;
}

.nav-menu {
  height: 100%;
  border-right: none;
}

.nav-menu:not(.el-menu--collapse) {
  width: 220px;
}

.content {
  padding: 20px;
  background: #f5f7fa;
}

.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 14px;
}

.el-breadcrumb__item:hover {
  color: #409eff;
  cursor: pointer;
}

.content-body {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  min-height: calc(100% - 40px);
}


</style>
